package com.adjy.pathbuilders.objects;

import org.jbox2d.dynamics.contacts.Contact;

import com.adjy.pathbuilders.physics.MovementType;
import com.adjy.pathbuilders.physics.PhysicalObject;
import com.adjy.pathbuilders.rendering.AnimationPack;
import com.adjy.pathbuilders.sounds.SoundManager;
import com.adjy.pathbuilders.world.GameEntity;
import com.adjy.pathbuilders.world.GameWorld;
import com.adjy.pathbuilders.world.Level;
import com.adjy.pathbuilders.world.MainChar;
import com.adjy.pathbuilders.world.StageProgress;

public class Door extends GameEntity implements Thinkable {

	private final static long SECONDS_TO_PASS = 1;
	private long firstTimeStopped = -1;
	public static final float[] SIZE = {4, 4};
	
	private MainChar player;
	private boolean isOpen;

	public Door(float x, float y, AnimationPack ap, Level parent) {
		super(GameEntityType.DOOR, x, y, SIZE[0], SIZE[1], ap, false, false, false);
		isOpen=true;
		this.closeDoor();
	}
	
	@Override
	public void hasStartedCollidingWith(PhysicalObject pObject, Contact contact) {
		if (pObject == null)
			return;
		if(((GameEntity) pObject).getType().equals(GameEntityType.MAINCHAR)) {
			this.openDoor();
			
			player = ((MainChar) pObject);
			player.setMovementType(MovementType.STOPPED);
			
			if (firstTimeStopped == -1)
				firstTimeStopped = System.currentTimeMillis();

		}
	}
	
	private void closeDoor() {
		if(isOpen) {
			this.isOpen = false;
			setAnimation("door_closed");
		}
	}
	
	// the open door (evanescence)
	private void openDoor() {
		if(!isOpen) {
			this.isOpen = true;
			SoundManager.getInstance().playSoundEffect("door");
			setAnimation("door_openning");
		}
	}
	
	public boolean isOpen() {
		return isOpen;
	}

	@Override
	public void think(GameWorld gameWorld, float timePassed) {
		if (firstTimeStopped != -1) {
			if (System.currentTimeMillis() - firstTimeStopped > SECONDS_TO_PASS * 1000) { // Expired
				player.setCurrentStageProgress(StageProgress.FINISHED);
			}
		}
		
	}

}
